package com.tangsm.spring.boot.websocket.controller;

import com.tangsm.spring.boot.websocket.domain.SysUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

/**
 * 登录页面
 *
 * @author tangsm
 */
@Slf4j
@Controller
public class LoginController {
    /**
     * 登录页面
     *
     * @param model 模型
     * @return 登录页面
     */
    @GetMapping(value = {"/", "/login"})
    public String login(Model model) {
        model.addAttribute("name", "SpringBoot");
        // 返回模板文件的名称
        return "login";
    }

    @PostMapping("/login")
    public String login(String username, String password, HttpSession session, Model model) {
        log.info("用户名：{}，密码：{}", username, password);
        //验证用户是否合法
        if (StringUtils.isNotBlank(username) && "123456".equals(password)) {
            SysUser user = new SysUser();
            user.setLoginName(username);
            user.setPassword(password);
            // 将登录用户保存到session
            session.setAttribute("loginUser", user);
            return "redirect:/index";
        }

        // 不合法，就重新登录, 请求转发
        model.addAttribute("msg", "账号/用户错误");
        return "login";
    }

    /**
     * 首页
     *
     * @param model 模型
     * @return 登录页面
     */
    @GetMapping(value = {"/index"})
    public String index(HttpSession session, Model model) {
        Object loginUser = session.getAttribute("loginUser");
        if (loginUser == null) {
            //回到登录页面
            model.addAttribute("msg", "请重新登录");
            return "login";
        }

        List<SysUser> users = new ArrayList<>();
        users.add(new SysUser(1L, "guanyu", "关羽", "男"));
        users.add(new SysUser(2L, "zhangfei", "张飞", "男"));
        users.add(new SysUser(3L, "zhaoyun", "赵云", "男"));
        users.add(new SysUser(4L, "machao", "马超", "男"));
        users.add(new SysUser(5L, "wangzhong", "黄忠", "男"));
        users.add(new SysUser(6L, "diaochan", "貂蝉", "女"));

        model.addAttribute("loginUser", loginUser);
        model.addAttribute("users", users);
        // 返回模板文件的名称
        return "index";
    }
}
